﻿using System.Linq;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Filters;
using TemplateFoundation.Configuration;
using TemplateFoundation.Exceptions;

namespace TemplateFoundation.Tags
{
    /// <summary>
    /// Extension methods for working with tags
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// Returns the associated tag page, if any
        /// </summary>
        /// <param name="tag">The tag for which the corresponding tag page should be retrieved</param>
        /// <returns></returns>
        public static PageReference GetPageLink(this Tag tag)
        {
            return GetPageLink(tag.Name);
        }

        /// <summary>
        /// Returns the associated tag page, if any
        /// </summary>
        /// <param name="category">A category with the same name as an existing tag</param>
        /// <returns></returns>
        public static PageReference GetPageLink(this Category category)
        {
            return GetPageLink(category.Name);
        }

        /// <summary>
        /// Returns the tag page corresponding to the tag name
        /// </summary>
        /// <returns></returns>
        private static PageReference GetPageLink(string name)
        {
            if(PageReference.IsNullOrEmpty(Settings.Instance.TagsContainer))
            {
                throw new TemplateFoundationException("No tag container page specified in site settings, please set the 'TagsContainer' property");
            }

            var criterias = new PropertyCriteriaCollection();

            criterias.Add(new PropertyCriteria()
                              {
                                  Name = "PageName",
                                  Required = true,
                                  Value = name,
                                  Condition = CompareCondition.Equal,
                                  Type=PropertyDataType.String
                              });

            var result = DataFactory.Instance.FindPagesWithCriteria(Settings.Instance.TagsContainer, criterias);

            if(!result.Any())
            {
                return PageReference.EmptyReference;
            }

            return result[0].PageLink;
        }
    }
}
